package niuke;

/**
 * Created by linshuo on 2018/3/2.
 *
 * 建个栈,并带有查找最小值的功能
 */
public class StackGetMin {
    private int[] data = new int[10];

    private int size = 0;

    public void push(int node) {
        expand();
        data[size] = node;
        size++;
    }

    public void pop() {
        if (size == 0)
            return;
        size--;
        shrink();
    }

    public int peer() {
        return data[size-1];
    }

    public int min() {
        if (size == 0)
            return 0;
        int min = data[0];
        for (int i = 1; i < size; i++) {
            if (min > data[i]) {
                min = data[i];
            }
        }
        return min;
    }

    private void expand() {
        if (size >= getCapacity()) {
            int[] newArray = new int[getCapacity() << 1];
            for (int i = 0; i < getCapacity(); i++) {
                newArray[i] = data[i];
            }
            data = newArray;
        }
    }

    private void shrink() {
        if (size <= (getCapacity() >> 2)) {
            int[] newArray = new int[getCapacity() >> 2];
            for (int i = 0; i < (getCapacity() >> 2); i++) {
                newArray[i] = data[i];
            }
            data = newArray;
        }
    }

    private int getCapacity() {
        return data.length;
    }

    public static void main(String[] args) {
        StackGetMin stack = new StackGetMin();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(5);
        stack.pop();
        System.out.println(stack.peer());
        System.out.println(stack.min());

    }
}
